package chpt09.testsync;

import java.util.concurrent.atomic.AtomicInteger;

public class SynchronizedThreadAtomicTest {

	public static void main(String[] args) throws InterruptedException {
		int n = 100000;
		CounterAtomic ca = new CounterAtomic();
		Thread t1 = new Thread(new AdderAtomic(ca, n));
		Thread t2 = new Thread(new AdderAtomic(ca, n));
		Thread t3 = new Thread(new AdderAtomic(ca, n));

		Thread t4 = new Thread(new SubtracterAtomic(ca, n));
		Thread t5 = new Thread(new SubtracterAtomic(ca, n));
		Thread t6 = new Thread(new SubtracterAtomic(ca, n));

		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
		t6.start();

		t1.join();
		t2.join();
		t3.join();
		t4.join();
		t5.join();
		t6.join();

		System.out.println(ca.getValue());
		System.out.println("main end");

	}

}

class CounterAtomic {
	private AtomicInteger id = new AtomicInteger(0);

	public void inc() {
		id.incrementAndGet();
	}
	public void dec() {
		id.decrementAndGet();
	}

	public int getValue() {
		return id.get();
	}
}

class AdderAtomic implements Runnable {
	private int n; // 执行次数
	private CounterAtomic counter;

	public AdderAtomic(CounterAtomic counter, int n) {
		this.counter = counter;
		this.n = n;
	}

	@Override
	public void run() {
		for (int i = 0; i < n; i++)
			counter.inc();
		String name = Thread.currentThread().getName();
		System.out.println(name + " end");
	}

}

class SubtracterAtomic implements Runnable {
	private int n; // 执行次数
	private CounterAtomic counter;

	public SubtracterAtomic(CounterAtomic counter, int n) {
		this.counter = counter;
		this.n = n;
	}

	@Override
	public void run() {
		for (int i = 0; i < n; i++)
			counter.dec();
		String name = Thread.currentThread().getName();
		System.out.println(name + " end");
	}
}
